package com.until;

import lombok.Data;

/**
 * @ Author xsd
 * @ crate time 2020/5/27 16:24
 * @ 描述
 */
@Data
public class XssUtil {
    private static final String EVENTS = "((?i) onload|onunload|onchange|onsubmit|onreset"
            + "|onselect|onblur|onfocus|onkeydown|onkeypress|onkeyup|onerror|onmouseenter|prompt"
            + "|script|alert"
            + "|onclick|ondblclick|onmousedown|onmousemove|onmouseout|onfScripTocus|alscRiPtert|onmouseover|onmouseup|onmouseenter)";

    private static final String XSS_HTML_TAG = "(%3C)|(%3E)|[<>]+|<|>";
    private static final String XSS_HTML_TRANs_TAG = "&#x([a-zA-Z0-9]{2,3})";

    private static final String XSS_HTML_TRANS_TAG_ = "&#([a-zA-Z0-9]{2,3})";

    private static final String XSS_INJECTION = "((%22%20)|(%22\\s)|('%22)|(%22\\+))\\w.*|(\\s|%20)"
            + EVENTS + ".*|(%3D)|(%7C)";
    private static final String XSS_REGEX = XSS_HTML_TAG + "|" + XSS_INJECTION;

    private static final String SQL_REGEX = "('.+--)|(--)|(\\|)|(%7C)";

    private static final String HTTPEVENTS = "((?i)href|location|window|src|<|>|%3C|%3E)";


    static boolean filterXSS = true;
    static boolean filterSQL = true;
    static boolean filterWhite=true;
    static boolean filterHttpXss=false;

    private static boolean isFilterHttpXss() {
        return filterHttpXss;
    }

    public static String filterParamString(String rawValue) {
        if (rawValue == null) {
            return null;
        }
        if ("".equals(rawValue)) {
            return null;
        }
        rawValue = rawValue.replaceAll("<", "&lt;").replaceAll(">", "&gt;");
        rawValue = rawValue.replaceAll("(.*)&lt;(.*)", "*").replaceAll("(.*)&gt;(.*)", "*");
        rawValue = rawValue.replaceAll("'", "’");
        if (filterXSS()) {
            rawValue = rawValue.replaceAll(XSS_REGEX, "-");
            rawValue = rawValue.replaceAll(XSS_HTML_TRANs_TAG, "*");
            rawValue = rawValue.replaceAll(XSS_HTML_TRANS_TAG_, "*");
        }
        if (filterSQL()) {
            rawValue = rawValue.replaceAll(SQL_REGEX, "-");
        }
        if(isFilterWhite()){
            rawValue = rawValue.replaceAll(EVENTS, "*");
        }
        if(isFilterHttpXss()){
            rawValue = rawValue.replaceAll(HTTPEVENTS, "*");
        }
        return rawValue;
    }
    private static boolean filterXSS() {
        return filterXSS;
    }

    private static boolean filterSQL() {
        return filterSQL;
    }

    private static boolean isFilterWhite() {
        return filterWhite;
    }
}
